package com.zhangzhi.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhangzhi.common.sql.DBHelper;
import com.zhangzhi.pagination.PaginationBase;
import com.zhangzhi.service.OrderService;
import com.zhangzhi.util.CosUpload;
import com.zhangzhi.util.DateUtil;
import com.zhangzhi.util.ExcelUtil;

@Controller
public class OrderDetailController extends PaginationBase {

	@Resource(name = "orderNSrevice")
	private OrderService orderNService;

	@RequestMapping(value = "/index.do", method = RequestMethod.GET)
	public ModelAndView main() {
		System.out.println("调用到了~~~~");
		return new ModelAndView("index");
	}

	@ResponseBody
	@RequestMapping(value = "/importExcel.do")
	public String importExcel(HttpServletRequest request) {
		JSONObject obj = new JSONObject();
		String saveDirectory = request.getRealPath("/") + "upload";
		try {
			String savedFileName = CosUpload.save(request, saveDirectory,
					1024 * 1024 * 2);
			File file = new File(savedFileName);
			if (file.exists()) {
				InputStream inputStream = new FileInputStream(file);
				HSSFWorkbook wb = new HSSFWorkbook(inputStream);
				HSSFSheet sheet = wb.getSheetAt(0);
				if (sheet == null) {

				}
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
					Map<String, Object> map = new HashMap<String, Object>();
					HSSFRow row = sheet.getRow(rowNum);
					double dateStr = row.getCell(0).getNumericCellValue();
					Date date = org.apache.poi.ss.usermodel.DateUtil
							.getJavaDate(dateStr);
					Date dateF = DateUtil.string2DateYYMMDD(sdf.format(date));
					String companyName = ExcelUtil.getValue(row.getCell(1));
					String measurement = ExcelUtil.getValue(row.getCell(2));
					String size = ExcelUtil.getValue(row.getCell(3));
					String measurement_out = ExcelUtil.getValue(row.getCell(4));
					String size_out = ExcelUtil.getValue(row.getCell(5));
					String height = ExcelUtil.getValue(row.getCell(7));
					String type = ExcelUtil.getValue(row.getCell(8));
					Map<String, Object> orderNumMap = new HashMap<String, Object>();
					orderNumMap.put("newOrderNo", "");
					orderNumMap = orderNService.getOrderNum(orderNumMap);
					map.put("ordernum", orderNumMap.get("newOrderNo"));
					map.put("companyname", companyName);
					map.put("createdate", dateF);
					map.put("measurement", measurement);
					map.put("size", size);
					map.put("measurement_out", measurement_out);
					map.put("size_out", size_out);
					map.put("height", height);
					if ("入".equals(type)) {
						map.put("type", 1);
					} else if ("出".equals(type)) {
						map.put("type", -1);
					} else {
						obj.put("statusCode", 300);
						obj.put("message", "导入数据类型为空或者不正确");
						obj.put("filename", "");
						return obj.toString();
					}
					list.add(map);
				}
				SqlSession session = DBHelper.getInstance().getBatchSession();
				session.insert("com.zhangzhi.dao.OrderDao.batchInsertOrder",
						list);
				session.commit();
				session.close();
				obj.put("statusCode", 200);
				obj.put("message", "导入数据成功");
				obj.put("filename", savedFileName);
			}
			return obj.toString();
		} catch (IOException e) {
			obj.put("statusCode", 300);
			obj.put("message", "网络异常或者文件超出2M！");
			obj.put("filename", "");
			return obj.toString();
		}
	}

	@RequestMapping(value = "/query.do")
	public ModelAndView query(HttpServletRequest request,
			Map<String, Object> model) {
		String strSize = request.getParameter("pageSize");
		String pn = request.getParameter("pageCurrent");
		Integer totalNum = orderNService.selectTotalOrderNum();
		if (null == pn || "".equals(pn)) {
			pn = "1";
		}
		this.getPage().setPageNo(Integer.valueOf(pn));
		if (strSize != null)
			this.getPage().setLimit(Integer.valueOf(strSize));
		this.getPage().setTotalRows(totalNum);

		Map<String, Object> pageObj = new HashMap<String, Object>();
		pageObj.put("offset", this.getPage().getOffset());
		pageObj.put("pagesize", this.getPage().getLimit());
		List<Map<String, Object>> results = orderNService
				.selectOrderByPagination(pageObj);

		this.getPage().setResultList(results);

		model.put("results", this.getPage().getResultList());
		model.put("pageCurrent", this.getPage().getPageNo());
		model.put("pageSize", this.getPage().getLimit());
		System.out.println(this.getPage().getLimit());
		model.put("totalNum", this.getPage().getTotalRows());
		return new ModelAndView("repertory-data", model);
	}

	@RequestMapping(value = "toDownLoadExcel")
	public ModelAndView toDownLoadExcel(HttpServletRequest request,
			Map<String, Object> model) {
		return new ModelAndView("downLoadExcel", model);
	}
}
